import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';
import { UiserviceProvider } from '../../providers/uiservice/uiservice';
import { BusiserviceProvider } from '../../providers/busiservice/busiservice';
import { LoadingUtil } from '../../common/loading';

/**
 * Generated class for the EcardlistPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-ecardlist',
  templateUrl: 'ecardlist.html',
})
export class EcardlistPage {
  searchtext: any = "";
  ecardList = [];
  userid: any;
  pagenum = 1;
  loading:LoadingUtil;
  constructor(public navCtrl: NavController, public navParams: NavParams, public uiservice: UiserviceProvider, public busi: BusiserviceProvider,private loadingCtrl: LoadingController) {
    this.userid = localStorage.getItem("userid");
    this.loading = new LoadingUtil(this.loadingCtrl);

  }
  ionViewDidEnter(){
    this.getcardList();
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad EcardlistPage');
  }
  getcardList() {
    this.pagenum =1;
    this.loading.showLoading();
    this.busi.getCardList(this.pagenum,this.searchtext).subscribe(
      data => {
        this.loading.hideLoading();
        if (data._success) {
          this.ecardList = data.result;
        } else {
          this.uiservice.showAlert(data._message);
        }
      },
      error => {
        this.loading.hideLoading();
        this.uiservice.showAlert("网络异常!")
      }
    );
  }
  favOrUnfav(card) {
    this.busi.favOrUnfav(card.cardid).subscribe(
      data => {
        if (data._success) {
          if (card.fav == null) {
            card.fav = this.userid;
          } else {
            card.fav = null;
          }
        } else {
          this.uiservice.showAlert(data._message);
        }
      },
      error => {
        this.uiservice.showAlert("网络错误！");
      }
    );

  }
  doInfinite(infiniteScroll) {
      this.pagenum = this.pagenum + 1;
      this.busi.getCardList(this.pagenum,this.searchtext).subscribe(
        data => {
          infiniteScroll.complete();
          if (data._success && data.result.length>0) {
            this.ecardList =this.ecardList.concat(data.result);
          } else if(!data._success) {
            this.uiservice.showAlert(data._message);
          }
        },
        error => {
          infiniteScroll.complete();
          this.uiservice.showAlert("网络异常!")
        }
      );
  }
}
